from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QWidget, QApplication, QMessageBox
from myUi import Ui_myUi
import requests
import re
import os

# 在b站看视频学习却又不知道剩的视频有多长怎么办
# https://www.bilibili.com/read/cv7896755/

class MyWindow(QWidget, Ui_myUi):

    def __init__(self):
        super(MyWindow, self).__init__()
        self.setupUi(self)
        self.initUI()   # 自己定义的函数

    # 在这里处理组件之间的串联工作
    def initUI(self):
        self.pushButton.clicked.connect(self.handle)

    def handle(self):
        try:
            bv = self.BV.text()
            start = int(self.start.text())
            end = int(self.end.text())
            url = 'https://www.bilibili.com/video/' + bv
            file_name = url.split('/')[-1] + '.html'
            if not os.path.exists(file_name):
                self.save_html(url)
            if end == '':
                str1, _ = self.handel_data(file_name, start)
            else:
                str1, _ = self.handel_data(file_name, start, end)

            # 今日看的
            self.allTimei_j.setText(str1)
            # 已经看的
            already, already_seconds = self.handel_data(file_name, 1, end)
            self.allTime_4.setText(self.end.text())  # 已经看的集数
            self.allTime_3.setText(already)  # 已经看的总时长
            # 未看的
            noready, _ = self.handel_data(file_name, end + 1)
            self.allTime_2.setText(noready)
            # 总时间
            str2, total_seconds = self.handel_data(file_name, 1)
            self.allTime.setText(str2)
            # 总时间对比
            self.percent.setText('{:.0%}'.format(already_seconds / total_seconds))


        except Exception as e:
            QMessageBox.information(self, "错误", str(e),
                                    QMessageBox.Yes)  # 最后的Yes表示弹框的按钮显示为Yes，默认按钮显示为OK,不填QMessageBox.Yes即为默认

    # 处理函数
    def save_html(self,url):
        '''
        url:对应视频的url链接
        保存对应视频的html源码文件
        '''
        res = requests.get(url)
        res.encoding = "utf-8"
        name = url.split('/')[-1]
        with open(f"{name}.html", "w", encoding='utf-8') as fp:
            fp.write(res.text)

    def handel_data(self, file, start=1, end=-1):
        '''
        file: html文件
        start: 选集起始 默认为第1集
        end: 选集结束 默认为最后1集
        '''
        with open("{}".format(file), "r", encoding="utf-8") as fp:
            data = fp.read()
        # 得到播放列表所有选集信息
        pageList = re.findall(
            r"<script>window.__INITIAL_STATE__=(.*?)</script>", data, re.MULTILINE)

        # 得到page part duration 对应选集集数 选集名字 选集时长(second)
        pages = re.findall(
            r'{"cid":.*?,"page":(.*?),"from":"vupload","part":(.*?),"duration":(\d*),"vid":.*?,"weblink":.*?,"dimension":.*?}',
            pageList[0])
        if end == -1:
            total_seconds = sum(int(page[-1]) for page in pages[start - 1:])
        else:
            total_seconds = sum(int(page[-1]) for page in pages[start - 1:end])
        hour = int(total_seconds / 60 / 60)
        minute = int((total_seconds - hour * 60 * 60) / 60)
        second = total_seconds - hour * 60 * 60 - minute * 60
        str = '{:02d}:{:02d}:{:02d}'.format(hour, minute, second)
        return str, total_seconds
        print('选集总时长为:{:02d}:{:02d}:{:02d}'.format(hour, minute, second))

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    myshow = MyWindow()         # 创建对象
    myshow.show()               # 显示对象
    sys.exit(app.exec_())
